﻿// Copyright (c) Vitaly Kamiansky. All rights reserved. 
// See License.txt in the project root.

using System;
using System.ComponentModel;

namespace Property.Reloaders
{
    public class CallbackReloader<T> : OutReloader<T>
    {
        public CallbackReloader(IWorkerPrototype<T> workerPrototype, Func<T> getValue, Action<T> applyValue, Action<bool> applyStatus)
            : base(applyValue, applyStatus)
        {
            if (workerPrototype == null) throw new ArgumentNullException("workerPrototype");

            _Worker = workerPrototype.Create(getValue);

            if (_Worker == null)
                throw new NotSupportedException(StringsCallbacks.CANT_OBTAIN_WORKER);

            _Worker.Finished += ResultReceived;
        }

        //=//

        private readonly IWorker<T> _Worker;

        public override void Go()
        {
            _ApplyStatus(true);
            _Worker.Go();
        }

        private void ResultReceived(object sender, EventArgs e)
        {
            if (_Worker.Exception != null) throw _Worker.Exception;

            _ApplyStatus(false);
            _ApplyValue(_Worker.Result);
        }

        public override void Dispose()
        {
            _Worker.Finished -= ResultReceived;
            _Worker.Dispose();
            base.Dispose();
        }
    }
}
